<?php

namespace App\Console\Commands\Controller;

use App\Common\Libs\Ali\Oss;
use App\Common\Libs\ArrayHelper;
use App\Console\BaseCommand;
use App\Consts\GlobalConst;
use App\Consts\GlobalCounterConst;
use App\Consts\GlobalUploadConst;
use App\Consts\GlobalUserRecommendConst;
use App\Models\Cache\Cache;
use App\Models\Cache\CacheKey;
use App\Models\FakeArticle;
use App\Models\LibraryUserAvatar;
use App\Models\User;
use App\Models\UserRecommend;

class UserRecommendCommand extends BaseCommand
{
    protected $signature = 'controller:user-recommend {action} {json}';

    protected $description = 'user-recommend commands';

    /**
     * 修改推荐列表，人物头像区域
     *
     * >=3真人推荐，使用前三个推荐用户的头像
     * <3真人推荐，使用机器人头像填充，直到达到3人推荐
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function avatarArea($data)
    {
        // 获取前三个真实推荐用户ID
        $userIdArr = [];
        for ($tableCount = 0; $tableCount < GlobalConst::DATABASE_TABLE_NUM; $tableCount++) {
            $tbName = UserRecommend::getTableNameByTableIndex($tableCount);
            $models = UserRecommend::setTableName($tbName)
                ->select(['user_id'])
                ->where([
                    'target_id' => $data['target_id'],
                    'is_deleted' => GlobalConst::IS_NOT_DELETE,
                ])
                ->get();
            $userIdArr = ArrayHelper::merge($userIdArr, ArrayHelper::getColumn($models, 'user_id'));
        }
        $userIdArr = array_slice($userIdArr, 0, GlobalUserRecommendConst::RECOMMEND_AVATAR_AREA_COUNT);

        // 获取用户头像
        $users = User::getModel()
            ->select(['avatar'])
            ->whereIn('user_id', (array)$userIdArr)
            ->get();
        $userAvatarArr = [];
        foreach ($users as $user) {
            $userAvatarArr[] = $user->avatar ?: GlobalConst::DEFAULT_AVATAR;
        }

        // 真实用户头像不足，使用头像库补足
        $libraryUserAvatarArr = [];
        if (count($userAvatarArr) < GlobalUserRecommendConst::RECOMMEND_AVATAR_AREA_COUNT) {
            $avatarCount = GlobalUserRecommendConst::RECOMMEND_AVATAR_AREA_COUNT - count($userAvatarArr);
            $libraryUserAvatars = LibraryUserAvatar::getInstance()
                ->select(['avatar'])
                ->where('is_deleted', GlobalConst::IS_NOT_DELETE)
                ->get();
            $libraryUserAvatarArr = collect(ArrayHelper::getColumn($libraryUserAvatars, 'avatar'))->random($avatarCount);
        }

        $avatars = ArrayHelper::merge($userAvatarArr, $libraryUserAvatarArr);

        // 上传到OSS
        Oss::getInstance(GlobalUploadConst::RECOMMEND_LIST_AVATAR_AREA)
            ->uploadTarget($avatars, true, $data['target_id'] . '.json');

        // 设置文章初始值
        $this->setArticleRecommendInitValue($data['target_id']);

        return true;
    }

    /**
     * @param $articleId
     * @return FakeArticle|bool|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    private function setArticleRecommendInitValue($articleId)
    {
        $model = FakeArticle::getModel()->where(['article_id' => $articleId])->first();
        if ($model) {
            return $model;
        }

        $count = random_int(10, 20);
        $model = FakeArticle::getModel()->create([
            'article_id' => $articleId,
            'action_type' => GlobalCounterConst::ACTION_TYPE_RECOMMEND,
            'count' => $count,
        ]);

        Cache::getInstance([
            'article_id' => $articleId,
        ])->incrFromArray(CacheKey::COUNTER_ARTICLE, GlobalCounterConst::FAKE_RECOMMEND, $count);

        return $model ?: false;
    }
}
